<?php

namespace app\admin\controller\xyvenue;

use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;
use app\admin\model\xyvenue\store\Store as StoreModel;
use app\admin\model\xyvenue\Venue as VenueModel;
use app\admin\model\xyvenue\order\Item as OrderItem;
use Exception;

/**
 * 定场订单管理
 *
 * @icon fa fa-circle-o
 */
class Package extends Backend
{

    /**
     * Package模型对象
     * @var \app\admin\model\xyvenue\Package
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\xyvenue\Package;
        $this->view->assign("typeList", $this->model->getTypeList());

    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['store','venue','user'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        
        //检测包场场地是否已经被预定
        $arealist = json_decode($params['arealist'],true);
        $timelist = json_decode($params['timelist'],true);
        $startdate = $params['startdate'];
        $enddate = $params['enddate'];

        if($startdate > $enddate){
            $this->error(__('开始日期不能小于结束日期', ''));
        }

        foreach($arealist as $area){
            foreach($timelist as $time){
                //检测区域时段是否已预定
                $isYd = OrderItem::where([
                        'date'=>['between', [$startdate, $enddate]],
                        'store_id'=>$params['store_id'],
                        'venue_id'=>$params['venue_id'],
                        'area'=>$area,
                        'starttime'=>explode('-',$time)[0],
                        'endtime'=>explode('-',$time)[1],
                        'status'=>['in',[0,1,2]]
                    ])->find();
                if(!empty($isYd)){
                    $this->error(__('时段内存在已被预定区域，请重新选择。', ''));
                }
            }
        }

        //检测包场是否存在
        while (strtotime($startdate) <= strtotime($enddate)) {
            foreach($arealist as $area){
                foreach($timelist as $time){
                    //检测区域时段是否已预定
                    $isYd = $this->model::where([
                            'startdate'=>['<=', $startdate],
                            'enddate'=>['>=', $startdate],
                            'store_id'=>$params['store_id'],
                            'venue_id'=>$params['venue_id'],
                            'arealist'=>['like','%'.$area.'%'],
                            'timelist'=>['like','%'.$time.'%'],
                        ])->find();

                    if(!empty($isYd)){
                        $this->error(__('时段内存在包场信息，请重新选择。', ''));
                    }
                }
            }
            $startdate = date ("Y-m-d", strtotime("+1 days", strtotime($startdate)));
        }

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $storeInfo = StoreModel::get($row['store_id']);
            $venueInfo = VenueModel::get($row['venue_id']);
            $this->assignconfig('storeInfo',$storeInfo);
            $this->assignconfig('venueInfo',$venueInfo);
            $this->assignconfig('row',$row);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);


        //检测包场场地是否已经被预定
        $arealist = json_decode($params['arealist'],true);
        $timelist = json_decode($params['timelist'],true);
        $startdate = $params['startdate'];
        $enddate = $params['enddate'];

        if($startdate > $enddate){
            $this->error(__('开始日期不能小于结束日期', ''));
        }

        foreach($arealist as $area){
            foreach($timelist as $time){
                //检测区域时段是否已预定
                $isYd = OrderItem::where([
                        'date'=>['between', [$startdate, $enddate]],
                        'store_id'=>$params['store_id'],
                        'venue_id'=>$params['venue_id'],
                        'area'=>$area,
                        'starttime'=>explode('-',$time)[0],
                        'endtime'=>explode('-',$time)[1],
                        'status'=>['in',[0,1,2]]
                    ])->find();
                if(!empty($isYd)){
                    $this->error(__('时段内存在已被预定区域，请重新选择。', ''));
                }
            }
        }

        //检测包场是否存在
        while (strtotime($startdate) <= strtotime($enddate)) {
            foreach($arealist as $area){
                foreach($timelist as $time){
                    //检测区域时段是否已预定
                    $isYd = $this->model::where([
                            'id'    =>['<>',$row['id']],
                            'startdate'=>['<=', $startdate],
                            'enddate'=>['>=', $startdate],
                            'store_id'=>$params['store_id'],
                            'venue_id'=>$params['venue_id'],
                            'arealist'=>['like','%'.$area.'%'],
                            'timelist'=>['like','%'.$time.'%'],
                        ])->find();

                    if(!empty($isYd)){
                        $this->error(__('时段内存在包场信息，请重新选择。', ''));
                    }
                }
            }
            $startdate = date ("Y-m-d", strtotime("+1 days", strtotime($startdate)));
        }

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


}
